<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单商品名" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入订单商品名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户 ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户 ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:cwuserorder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:cwuserorder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:cwuserorder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:cwuserorder:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
           type="info"
          plain
          icon="el-icon-data-line"
          size="mini"
          @click="handleChart"
          v-hasPermi="['system:cwuserorder:query']"
        >图表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cwuserorderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单 ID" align="center" prop="orderId" />
      <el-table-column label="订单商品名" align="center" prop="orderName" />
      <el-table-column label="商品图片" align="center" prop="orderImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.orderImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="用户 ID" align="center" prop="userId" />
      <el-table-column label="接口ID" align="center" prop="interfaceInfoId" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" />
      <el-table-column label="下单时间(已支付、已发货、已签收、已取消)" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:cwuserorder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:cwuserorder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单商品名" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单商品名" />
        </el-form-item>
        <el-form-item label="商品图片" prop="orderImg">
          <image-upload v-model="form.orderImg"/>
        </el-form-item>
        <el-form-item label="用户 ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户 ID" />
        </el-form-item>
        <el-form-item label="接口ID" prop="interfaceInfoId">
          <el-input v-model="form.interfaceInfoId" placeholder="请输入接口ID" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="下单时间(已支付、已发货、已签收、已取消)" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下单时间(已支付、已发货、已签收、已取消)">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否删除" prop="isDelete">
          <el-radio-group v-model="form.isDelete">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 销售图表对话框 -->
    <el-dialog title="每日销售额统计" :visible.sync="chartDialogVisible" width="800px" append-to-body>
      <div ref="salesChart" style="width: 100%; height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chartDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCwuserorder, getCwuserorder, delCwuserorder, addCwuserorder, updateCwuserorder } from "@/api/system/cwuserorder";
import * as echarts from 'echarts';

export default {
  name: "Cwuserorder",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      cwuserorderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderName: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户 ID不能为空", trigger: "blur" }
        ],
      },
      // 图表对话框显示状态
      chartDialogVisible: false,
      // 图表实例
      chart: null,
      // 图表数据
      chartData: {
        dates: [],
        amounts: []
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      listCwuserorder(this.queryParams).then(response => {
        this.cwuserorderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderName: null,
        orderImg: null,
        userId: null,
        interfaceInfoId: null,
        totalAmount: null,
        paymentMethod: null,
        orderStatus: null,
        orderTime: null,
        orderNumber: null,
        updateTime: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getCwuserorder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateCwuserorder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCwuserorder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单管理编号为"' + orderIds + '"的数据项？').then(function() {
        return delCwuserorder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/cwuserorder/export', {
        ...this.queryParams
      }, `cwuserorder_${new Date().getTime()}.xlsx`)
    },
    /** 图表按钮操作 */
    handleChart() {
      this.chartDialogVisible = true;
      this.$nextTick(() => {
        this.initChart();
        this.getChartData();
      });
    },

    /** 初始化图表 */
    initChart() {
      this.chart = echarts.init(this.$refs.salesChart);
      const option = {
        title: {
          text: '每日销售额统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>销售额: {c}'
        },
        xAxis: {
          type: 'category',
          data: this.chartData.dates
        },
        yAxis: {
          type: 'value',
          name: '销售额'
        },
        series: [{
          data: this.chartData.amounts,
          type: 'line',
          smooth: true,
          areaStyle: {}
        }]
      };
      this.chart.setOption(option);
    },

    /** 获取图表数据 */
    getChartData() {
      // 从现有订单数据中提取每日销售额
      const dailySales = {};
      this.cwuserorderList.forEach(order => {
        const date = this.parseTime(order.orderTime, '{y}-{m}-{d}');
        if (!dailySales[date]) {
          dailySales[date] = 0;
        }
        dailySales[date] += parseFloat(order.totalAmount || 0);
      });

      // 转换为图表所需的数据格式
      const dates = Object.keys(dailySales).sort();
      const amounts = dates.map(date => dailySales[date]);

      this.chartData.dates = dates;
      this.chartData.amounts = amounts;
      
      // 更新图表
      this.chart.setOption({
        xAxis: {
          data: dates
        },
        series: [{
          data: amounts
        }]
      });
    }
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose();
    }
  }
};
</script>
